from socket import *
import sys,struct,time
myHost = ''                           
myPort = 50007                       
param = sys.argv[1:]
N_PEER,BUFFER,LOG = param
print N_PEER
print BUFFER
sockobj = socket(AF_INET, SOCK_STREAM)     
sockobj.bind((myHost, myPort))            
sockobj.listen(int(N_PEER))                        
#video = open('/home/zank/Desktop/tcc2/DESENVOLVIMENTO/provider/lost.avi', 'r')
video = open('/home/zank/Desktop/pes2009.mpg', 'r')
log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w')
Saida=False
count = 0
lista = []
payload = int(BUFFER)-24

while len(lista) < int(N_PEER):                                   
    connection, address = sockobj.accept() 
    print 'Server connected by', address   
    data = connection.recv(1024)
    print data
    if data.strip() == 'PLAY':
	lista.append([address,connection])
    else:
	pass

while 1:
        stream = video.read(payload)
	if len(stream) == 0:
		break
	count = count+1
	id = str(count)
	id = id.rjust(24,'0')
	data = struct.pack('24s'+str(payload)+'s',id,stream)
	for sock_obj in lista:
		try:
			sock_obj[1].send(data)
			log.write(str(int(id))+';')
			log.write(str(len(data))+';')
			log.write(str(sock_obj[0])+';')
			log.write(time.strftime('%H:%M:%S')+'\r\n')
		except:
			lista.remove(sock_obj)
log.close()
sockobj.close()
